// 标签页状态管理
// 实现多文件标签页管理系统，支持最多20个标签

import { createStore, BaseStore, createBaseState, createBaseActions } from './storeFactory';

// 标签页状态枚举
export enum TabStatus {
  Clean = 'clean',           // 已保存
  Modified = 'modified',     // 已修改
  New = 'new',              // 新文件
  Saving = 'saving',        // 保存中
  Error = 'error'           // 错误状态
}

// 标签页数据结构
export interface Tab {
  id: string;                // 唯一标识符
  filePath: string;          // 文件路径
  fileName: string;          // 文件名
  title?: string;            // 标签页标题（可选，默认使用fileName）
  content: string;           // 文件内容
  originalContent: string;   // 原始内容（用于比较是否修改）
  status: TabStatus;         // 标签页状态
  language: string;          // 编程语言
  encoding: string;          // 文件编码
  lineEnding: string;        // 行结束符
  cursorPosition: {          // 光标位置
    line: number;
    column: number;
  };
  selection?: {              // 选择范围
    start: { line: number; column: number };
    end: { line: number; column: number };
  };
  scrollPosition: {          // 滚动位置
    top: number;
    left: number;
  };
  isTemporary: boolean;      // 是否为临时标签（预览模式）
  isDirty?: boolean;         // 是否有未保存的更改
  lastAccessed?: number;     // 最后访问时间
  lastModified: number;      // 最后修改时间
  createdAt: number;         // 创建时间
  groupId?: string;          // 所属分组ID（可选）
}

// 标签页分组
export interface TabGroup {
  id: string;
  name: string;
  tabs: string[];            // 标签页ID列表
  isActive: boolean;         // 是否为活动分组
  color?: string;            // 分组颜色
}

// 标签页历史记录
export interface TabHistory {
  recentTabs: string[];      // 最近访问的标签页ID列表
  closedTabs: Tab[];         // 最近关闭的标签页
  maxRecentTabs: number;     // 最大最近标签页数量
  maxClosedTabs: number;     // 最大已关闭标签页数量
}

// 标签页配置
export interface TabConfig {
  maxTabs: number;           // 最大标签页数量
  autoSaveInterval: number;  // 自动保存间隔（毫秒）
  enableAutoSave: boolean;   // 是否启用自动保存
  enablePreview: boolean;    // 是否启用预览模式
  showCloseButton: boolean;  // 是否显示关闭按钮
  showModifiedIndicator: boolean; // 是否显示修改指示器
  tabWidth: 'auto' | 'fixed'; // 标签页宽度模式
  fixedTabWidth: number;     // 固定标签页宽度
}

// 标签页状态接口
export interface TabState {
  // 核心状态
  tabs: Map<string, Tab>;           // 所有标签页
  tabOrder: string[];               // 标签页顺序
  activeTabId: string | null;       // 当前活动标签页ID
  groups: Map<string, TabGroup>;    // 标签页分组
  activeGroupId: string | null;     // 当前活动分组ID
  history: TabHistory;              // 历史记录
  config: TabConfig;                // 配置
  
  // UI状态
  isLoading: boolean;               // 是否正在加载
  error: string | null;             // 错误信息
  draggedTabId: string | null;      // 正在拖拽的标签页ID
  dropTargetIndex: number | null;   // 拖拽目标位置
  
  // 搜索和过滤
  searchQuery: string;              // 搜索查询
  filteredTabs: string[];           // 过滤后的标签页ID列表
}

// 默认配置
const defaultConfig: TabConfig = {
  maxTabs: 20,
  autoSaveInterval: 30000, // 30秒
  enableAutoSave: true,
  enablePreview: true,
  showCloseButton: true,
  showModifiedIndicator: true,
  tabWidth: 'auto',
  fixedTabWidth: 200,
};

// 默认历史记录
const defaultHistory: TabHistory = {
  recentTabs: [],
  closedTabs: [],
  maxRecentTabs: 10,
  maxClosedTabs: 5,
};

// 工具函数：生成标签页ID
const generateTabId = (filePath: string): string => {
  return `tab_${filePath.replace(/[^a-zA-Z0-9]/g, '_')}_${Date.now()}`;
};

// 工具函数：检测文件语言
const detectLanguage = (filePath: string): string => {
  const ext = filePath.split('.').pop()?.toLowerCase() || '';
  const languageMap: Record<string, string> = {
    'js': 'javascript',
    'jsx': 'javascript',
    'ts': 'typescript',
    'tsx': 'typescript',
    'py': 'python',
    'java': 'java',
    'cpp': 'cpp',
    'c': 'c',
    'cs': 'csharp',
    'php': 'php',
    'rb': 'ruby',
    'go': 'go',
    'rs': 'rust',
    'html': 'html',
    'css': 'css',
    'scss': 'scss',
    'sass': 'sass',
    'json': 'json',
    'xml': 'xml',
    'yaml': 'yaml',
    'yml': 'yaml',
    'md': 'markdown',
    'txt': 'plaintext',
  };
  return languageMap[ext] || 'plaintext';
};

// 工具函数：检查标签页是否已修改
const isTabModified = (tab: Tab): boolean => {
  return tab.content !== tab.originalContent;
};

// 标签页操作接口
export interface TabActions {
  // 标签页基础操作
  openTab: (filePath: string, content?: string, options?: Partial<Tab>) => Promise<string>;
  closeTab: (tabId: string, force?: boolean) => Promise<boolean>;
  closeAllTabs: (force?: boolean) => Promise<boolean>;
  closeOtherTabs: (keepTabId: string, force?: boolean) => Promise<boolean>;
  closeTabsToRight: (tabId: string, force?: boolean) => Promise<boolean>;
  closeTabsToLeft: (tabId: string, force?: boolean) => Promise<boolean>;

  // 标签页切换和导航
  activateTab: (tabId: string) => void;
  activateNextTab: () => void;
  activatePreviousTab: () => void;
  activateTabByIndex: (index: number) => void;
  activateRecentTab: () => void;

  // 标签页内容操作
  updateTabContent: (tabId: string, content: string) => void;
  updateTabStatus: (tabId: string, status: TabStatus) => void;
  updateTabPosition: (tabId: string, position: Tab['cursorPosition']) => void;
  updateTabSelection: (tabId: string, selection: Tab['selection']) => void;
  updateTabScrollPosition: (tabId: string, scrollPosition: Tab['scrollPosition']) => void;

  // 标签页保存操作
  saveTab: (tabId: string) => Promise<boolean>;
  saveAllTabs: () => Promise<boolean>;
  saveTabAs: (tabId: string, newPath: string) => Promise<boolean>;

  // 标签页排序和分组
  reorderTabs: (newOrder: string[]) => void;
  moveTab: (tabId: string, targetIndex: number) => void;
  createGroup: (name: string, tabIds: string[]) => string;
  addTabToGroup: (tabId: string, groupId: string) => void;
  removeTabFromGroup: (tabId: string, groupId: string) => void;
  deleteGroup: (groupId: string) => void;
  activateGroup: (groupId: string) => void;

  // 历史记录操作
  addToRecentTabs: (tabId: string) => void;
  removeFromRecentTabs: (tabId: string) => void;
  addToClosedTabs: (tab: Tab) => void;
  reopenClosedTab: () => Tab | null;
  clearHistory: () => void;

  // 搜索和过滤
  setSearchQuery: (query: string) => void;
  filterTabs: (predicate: (tab: Tab) => boolean) => void;
  clearFilter: () => void;

  // 配置操作
  updateConfig: (config: Partial<TabConfig>) => void;
  resetConfig: () => void;

  // 拖拽操作
  startDrag: (tabId: string) => void;
  setDropTarget: (index: number | null) => void;
  endDrag: () => void;

  // 工具方法
  getTab: (tabId: string) => Tab | undefined;
  getActiveTab: () => Tab | undefined;
  getTabsByGroup: (groupId: string) => Tab[];
  getModifiedTabs: () => Tab[];
  hasUnsavedChanges: () => boolean;
  canCloseTab: (tabId: string) => boolean;
  generateTabId: (filePath: string) => string;

  // 编辑器操作
  canUndo: (tabId: string) => boolean;
  canRedo: (tabId: string) => boolean;
  undo: (tabId: string) => void;
  redo: (tabId: string) => void;

  // 会话管理
  saveSession: () => void;
  loadSession: () => void;
  clearSession: () => void;
}

// 完整的标签页Store类型
export type TabStore = BaseStore<TabState & TabActions>;

// 创建标签页Store
export const useTabStore = createStore<TabState & TabActions>(
  (set, get) => ({
    // 基础状态
    ...createBaseState(),

    // 标签页特定状态
    tabs: new Map(),
    tabOrder: [],
    activeTabId: null,
    groups: new Map(),
    activeGroupId: null,
    history: { ...defaultHistory },
    config: { ...defaultConfig },
    draggedTabId: null,
    dropTargetIndex: null,
    searchQuery: '',
    filteredTabs: [],

    // 基础操作
    ...createBaseActions(set, get),

        // 标签页基础操作
        openTab: async (filePath: string, content = '', options = {}) => {
          const state = get();

          // 检查是否已经打开
          const existingTab = Array.from(state.tabs.values()).find(tab => tab.filePath === filePath);
          if (existingTab) {
            get().activateTab(existingTab.id);
            return existingTab.id;
          }

          // 检查标签页数量限制
          if (state.tabs.size >= state.config.maxTabs) {
            set({ error: `最多只能打开 ${state.config.maxTabs} 个标签页` });
            return '';
          }

          const tabId = generateTabId(filePath);
          const fileName = filePath.split('/').pop() || filePath.split('\\').pop() || 'Untitled';
          const language = detectLanguage(filePath);

          const newTab: Tab = {
            id: tabId,
            filePath,
            fileName,
            content,
            originalContent: content,
            status: content ? TabStatus.Clean : TabStatus.New,
            language,
            encoding: 'utf-8',
            lineEnding: '\n',
            cursorPosition: { line: 1, column: 1 },
            scrollPosition: { top: 0, left: 0 },
            isTemporary: false,
            lastModified: Date.now(),
            createdAt: Date.now(),
            ...options,
          };

          set(state => ({
            tabs: new Map(state.tabs).set(tabId, newTab),
            tabOrder: [...state.tabOrder, tabId],
            activeTabId: tabId,
            error: null,
          }));

          // 添加到最近访问列表
          get().addToRecentTabs(tabId);

          return tabId;
        },

        closeTab: async (tabId: string, force = false) => {
          const state = get();
          const tab = state.tabs.get(tabId);

          if (!tab) return false;

          // 检查是否有未保存的更改
          if (!force && isTabModified(tab)) {
            // 这里应该显示确认对话框，暂时返回false
            set({ error: '文件有未保存的更改' });
            return false;
          }

          // 添加到已关闭标签页历史
          get().addToClosedTabs(tab);

          const newTabs = new Map(state.tabs);
          newTabs.delete(tabId);

          const newTabOrder = state.tabOrder.filter(id => id !== tabId);

          // 如果关闭的是活动标签页，需要激活其他标签页
          let newActiveTabId = state.activeTabId;
          if (state.activeTabId === tabId) {
            const currentIndex = state.tabOrder.indexOf(tabId);
            if (newTabOrder.length > 0) {
              // 优先激活右侧标签页，如果没有则激活左侧
              newActiveTabId = newTabOrder[currentIndex] || newTabOrder[currentIndex - 1] || null;
            } else {
              newActiveTabId = null;
            }
          }

          set({
            tabs: newTabs,
            tabOrder: newTabOrder,
            activeTabId: newActiveTabId,
            error: null,
          });

          return true;
        },

        closeAllTabs: async (force = false) => {
          const state = get();

          if (!force) {
            const modifiedTabs = Array.from(state.tabs.values()).filter(isTabModified);
            if (modifiedTabs.length > 0) {
              set({ error: `有 ${modifiedTabs.length} 个文件有未保存的更改` });
              return false;
            }
          }

          // 添加所有标签页到已关闭历史
          Array.from(state.tabs.values()).forEach(tab => {
            get().addToClosedTabs(tab);
          });

          set({
            tabs: new Map(),
            tabOrder: [],
            activeTabId: null,
            error: null,
          });

          return true;
        },

        closeOtherTabs: async (keepTabId: string, force = false) => {
          const state = get();
          const keepTab = state.tabs.get(keepTabId);

          if (!keepTab) return false;

          if (!force) {
            const modifiedTabs = Array.from(state.tabs.values())
              .filter(tab => tab.id !== keepTabId && isTabModified(tab));
            if (modifiedTabs.length > 0) {
              set({ error: `有 ${modifiedTabs.length} 个文件有未保存的更改` });
              return false;
            }
          }

          // 添加其他标签页到已关闭历史
          Array.from(state.tabs.values()).forEach(tab => {
            if (tab.id !== keepTabId) {
              get().addToClosedTabs(tab);
            }
          });

          set({
            tabs: new Map([[keepTabId, keepTab]]),
            tabOrder: [keepTabId],
            activeTabId: keepTabId,
            error: null,
          });

          return true;
        },

        closeTabsToRight: async (tabId: string, force = false) => {
          const state = get();
          const tabIndex = state.tabOrder.indexOf(tabId);

          if (tabIndex === -1 || tabIndex === state.tabOrder.length - 1) return false;

          const tabsToClose = state.tabOrder.slice(tabIndex + 1);

          if (!force) {
            const modifiedTabs = tabsToClose
              .map(id => state.tabs.get(id))
              .filter(tab => tab && isTabModified(tab));
            if (modifiedTabs.length > 0) {
              set({ error: `有 ${modifiedTabs.length} 个文件有未保存的更改` });
              return false;
            }
          }

          // 添加到已关闭历史
          tabsToClose.forEach(id => {
            const tab = state.tabs.get(id);
            if (tab) get().addToClosedTabs(tab);
          });

          const newTabs = new Map(state.tabs);
          tabsToClose.forEach(id => newTabs.delete(id));

          const newTabOrder = state.tabOrder.slice(0, tabIndex + 1);

          set({
            tabs: newTabs,
            tabOrder: newTabOrder,
            error: null,
          });

          return true;
        },

        closeTabsToLeft: async (tabId: string, force = false) => {
          const state = get();
          const tabIndex = state.tabOrder.indexOf(tabId);

          if (tabIndex === -1 || tabIndex === 0) return false;

          const tabsToClose = state.tabOrder.slice(0, tabIndex);

          if (!force) {
            const modifiedTabs = tabsToClose
              .map(id => state.tabs.get(id))
              .filter(tab => tab && isTabModified(tab));
            if (modifiedTabs.length > 0) {
              set({ error: `有 ${modifiedTabs.length} 个文件有未保存的更改` });
              return false;
            }
          }

          // 添加到已关闭历史
          tabsToClose.forEach(id => {
            const tab = state.tabs.get(id);
            if (tab) get().addToClosedTabs(tab);
          });

          const newTabs = new Map(state.tabs);
          tabsToClose.forEach(id => newTabs.delete(id));

          const newTabOrder = state.tabOrder.slice(tabIndex);

          set({
            tabs: newTabs,
            tabOrder: newTabOrder,
            error: null,
          });

          return true;
        },

        // 标签页切换和导航
        activateTab: (tabId: string) => {
          const state = get();
          if (state.tabs.has(tabId)) {
            set({ activeTabId: tabId });
            get().addToRecentTabs(tabId);
          }
        },

        activateNextTab: () => {
          const state = get();
          if (!state.activeTabId || state.tabOrder.length <= 1) return;

          const currentIndex = state.tabOrder.indexOf(state.activeTabId);
          const nextIndex = (currentIndex + 1) % state.tabOrder.length;
          const nextTabId = state.tabOrder[nextIndex];

          get().activateTab(nextTabId);
        },

        activatePreviousTab: () => {
          const state = get();
          if (!state.activeTabId || state.tabOrder.length <= 1) return;

          const currentIndex = state.tabOrder.indexOf(state.activeTabId);
          const prevIndex = currentIndex === 0 ? state.tabOrder.length - 1 : currentIndex - 1;
          const prevTabId = state.tabOrder[prevIndex];

          get().activateTab(prevTabId);
        },

        activateTabByIndex: (index: number) => {
          const state = get();
          if (index >= 0 && index < state.tabOrder.length) {
            const tabId = state.tabOrder[index];
            get().activateTab(tabId);
          }
        },

        activateRecentTab: () => {
          const state = get();
          if (state.history.recentTabs.length > 1) {
            // 激活最近访问的第二个标签页（第一个是当前活动的）
            const recentTabId = state.history.recentTabs[1];
            if (state.tabs.has(recentTabId)) {
              get().activateTab(recentTabId);
            }
          }
        },

        // 标签页内容操作
        updateTabContent: (tabId: string, content: string) => {
          const state = get();
          const tab = state.tabs.get(tabId);

          if (tab) {
            const updatedTab = {
              ...tab,
              content,
              status: content === tab.originalContent ? TabStatus.Clean : TabStatus.Modified,
              lastModified: Date.now(),
            };

            set(state => ({
              tabs: new Map(state.tabs).set(tabId, updatedTab),
            }));
          }
        },

        updateTabStatus: (tabId: string, status: TabStatus) => {
          const state = get();
          const tab = state.tabs.get(tabId);

          if (tab) {
            const updatedTab = { ...tab, status };
            set(state => ({
              tabs: new Map(state.tabs).set(tabId, updatedTab),
            }));
          }
        },

        updateTabPosition: (tabId: string, position: Tab['cursorPosition']) => {
          const state = get();
          const tab = state.tabs.get(tabId);

          if (tab) {
            const updatedTab = { ...tab, cursorPosition: position };
            set(state => ({
              tabs: new Map(state.tabs).set(tabId, updatedTab),
            }));
          }
        },

        updateTabSelection: (tabId: string, selection: Tab['selection']) => {
          const state = get();
          const tab = state.tabs.get(tabId);

          if (tab) {
            const updatedTab = { ...tab, selection };
            set(state => ({
              tabs: new Map(state.tabs).set(tabId, updatedTab),
            }));
          }
        },

        updateTabScrollPosition: (tabId: string, scrollPosition: Tab['scrollPosition']) => {
          const state = get();
          const tab = state.tabs.get(tabId);

          if (tab) {
            const updatedTab = { ...tab, scrollPosition };
            set(state => ({
              tabs: new Map(state.tabs).set(tabId, updatedTab),
            }));
          }
        },

        // 标签页保存操作
        saveTab: async (tabId: string) => {
          const state = get();
          const tab = state.tabs.get(tabId);

          if (!tab) return false;

          try {
            set(state => ({
              tabs: new Map(state.tabs).set(tabId, {
                ...tab,
                status: TabStatus.Saving,
              }),
            }));

            // 这里应该调用文件系统API保存文件
            // 暂时模拟保存操作
            await new Promise(resolve => setTimeout(resolve, 500));

            const updatedTab = {
              ...tab,
              originalContent: tab.content,
              status: TabStatus.Clean,
              lastModified: Date.now(),
            };

            set(state => ({
              tabs: new Map(state.tabs).set(tabId, updatedTab),
            }));

            return true;
          } catch (error) {
            set(state => ({
              tabs: new Map(state.tabs).set(tabId, {
                ...tab,
                status: TabStatus.Error,
              }),
              error: `保存文件失败: ${error}`,
            }));
            return false;
          }
        },

        saveAllTabs: async () => {
          const state = get();
          const modifiedTabs = Array.from(state.tabs.values()).filter(isTabModified);

          const results = await Promise.all(
            modifiedTabs.map(tab => get().saveTab(tab.id))
          );

          return results.every(result => result);
        },

        saveTabAs: async (tabId: string, newPath: string) => {
          const state = get();
          const tab = state.tabs.get(tabId);

          if (!tab) return false;

          try {
            // 这里应该调用文件系统API保存到新路径
            // 暂时模拟保存操作
            await new Promise(resolve => setTimeout(resolve, 500));

            const fileName = newPath.split('/').pop() || newPath.split('\\').pop() || 'Untitled';
            const language = detectLanguage(newPath);

            const updatedTab = {
              ...tab,
              filePath: newPath,
              fileName,
              language,
              originalContent: tab.content,
              status: TabStatus.Clean,
              lastModified: Date.now(),
            };

            set(state => ({
              tabs: new Map(state.tabs).set(tabId, updatedTab),
            }));

            return true;
          } catch (error) {
            set({ error: `另存为失败: ${error}` });
            return false;
          }
        },

        // 标签页排序和分组
        reorderTabs: (newOrder: string[]) => {
          set({ tabOrder: newOrder });
        },

        moveTab: (tabId: string, targetIndex: number) => {
          const state = get();
          const currentIndex = state.tabOrder.indexOf(tabId);

          if (currentIndex === -1 || targetIndex < 0 || targetIndex >= state.tabOrder.length) {
            return;
          }

          const newOrder = [...state.tabOrder];
          newOrder.splice(currentIndex, 1);
          newOrder.splice(targetIndex, 0, tabId);

          set({ tabOrder: newOrder });
        },

        createGroup: (name: string, tabIds: string[]) => {
          const groupId = `group_${Date.now()}`;
          const newGroup: TabGroup = {
            id: groupId,
            name,
            tabs: tabIds,
            isActive: false,
          };

          set(state => ({
            groups: new Map(state.groups).set(groupId, newGroup),
          }));

          return groupId;
        },

        addTabToGroup: (tabId: string, groupId: string) => {
          const state = get();
          const group = state.groups.get(groupId);

          if (group && !group.tabs.includes(tabId)) {
            const updatedGroup = {
              ...group,
              tabs: [...group.tabs, tabId],
            };

            set(state => ({
              groups: new Map(state.groups).set(groupId, updatedGroup),
            }));
          }
        },

        removeTabFromGroup: (tabId: string, groupId: string) => {
          const state = get();
          const group = state.groups.get(groupId);

          if (group) {
            const updatedGroup = {
              ...group,
              tabs: group.tabs.filter(id => id !== tabId),
            };

            set(state => ({
              groups: new Map(state.groups).set(groupId, updatedGroup),
            }));
          }
        },

        deleteGroup: (groupId: string) => {
          const state = get();
          const newGroups = new Map(state.groups);
          newGroups.delete(groupId);

          set({
            groups: newGroups,
            activeGroupId: state.activeGroupId === groupId ? null : state.activeGroupId,
          });
        },

        activateGroup: (groupId: string) => {
          const state = get();
          if (state.groups.has(groupId)) {
            set({ activeGroupId: groupId });
          }
        },

        // 历史记录操作
        addToRecentTabs: (tabId: string) => {
          const state = get();
          const recentTabs = state.history.recentTabs.filter(id => id !== tabId);
          recentTabs.unshift(tabId);

          if (recentTabs.length > state.history.maxRecentTabs) {
            recentTabs.splice(state.history.maxRecentTabs);
          }

          set(state => ({
            history: {
              ...state.history,
              recentTabs,
            },
          }));
        },

        removeFromRecentTabs: (tabId: string) => {
          const state = get();
          const recentTabs = state.history.recentTabs.filter(id => id !== tabId);

          set(state => ({
            history: {
              ...state.history,
              recentTabs,
            },
          }));
        },

        addToClosedTabs: (tab: Tab) => {
          const state = get();
          const closedTabs = [tab, ...state.history.closedTabs];

          if (closedTabs.length > state.history.maxClosedTabs) {
            closedTabs.splice(state.history.maxClosedTabs);
          }

          set(state => ({
            history: {
              ...state.history,
              closedTabs,
            },
          }));
        },

        reopenClosedTab: () => {
          const state = get();
          if (state.history.closedTabs.length === 0) return null;

          const [tabToReopen, ...remainingClosedTabs] = state.history.closedTabs;

          // 重新生成ID以避免冲突
          const newTabId = generateTabId(tabToReopen.filePath);
          const reopenedTab = {
            ...tabToReopen,
            id: newTabId,
            createdAt: Date.now(),
          };

          set(state => ({
            tabs: new Map(state.tabs).set(newTabId, reopenedTab),
            tabOrder: [...state.tabOrder, newTabId],
            activeTabId: newTabId,
            history: {
              ...state.history,
              closedTabs: remainingClosedTabs,
            },
          }));

          get().addToRecentTabs(newTabId);
          return reopenedTab;
        },

        clearHistory: () => {
          set(state => ({
            history: {
              ...state.history,
              recentTabs: [],
              closedTabs: [],
            },
          }));
        },

        // 搜索和过滤
        setSearchQuery: (query: string) => {
          set({ searchQuery: query });

          if (query.trim() === '') {
            set({ filteredTabs: [] });
          } else {
            const state = get();
            const filteredTabs = Array.from(state.tabs.values())
              .filter(tab =>
                tab.fileName.toLowerCase().includes(query.toLowerCase()) ||
                tab.filePath.toLowerCase().includes(query.toLowerCase())
              )
              .map(tab => tab.id);

            set({ filteredTabs });
          }
        },

        filterTabs: (predicate: (tab: Tab) => boolean) => {
          const state = get();
          const filteredTabs = Array.from(state.tabs.values())
            .filter(predicate)
            .map(tab => tab.id);

          set({ filteredTabs });
        },

        clearFilter: () => {
          set({ searchQuery: '', filteredTabs: [] });
        },

        // 配置操作
        updateConfig: (config: Partial<TabConfig>) => {
          set(state => ({
            config: { ...state.config, ...config },
          }));
        },

        resetConfig: () => {
          set({ config: { ...defaultConfig } });
        },

        // 拖拽操作
        startDrag: (tabId: string) => {
          set({ draggedTabId: tabId });
        },

        setDropTarget: (index: number | null) => {
          set({ dropTargetIndex: index });
        },

        endDrag: () => {
          const state = get();

          if (state.draggedTabId && state.dropTargetIndex !== null) {
            get().moveTab(state.draggedTabId, state.dropTargetIndex);
          }

          set({
            draggedTabId: null,
            dropTargetIndex: null,
          });
        },

        // 工具方法
        getTab: (tabId: string) => {
          return get().tabs.get(tabId);
        },

        getActiveTab: () => {
          const state = get();
          return state.activeTabId ? state.tabs.get(state.activeTabId) : undefined;
        },

        getTabsByGroup: (groupId: string) => {
          const state = get();
          const group = state.groups.get(groupId);

          if (!group) return [];

          return group.tabs
            .map(tabId => state.tabs.get(tabId))
            .filter((tab): tab is Tab => tab !== undefined);
        },

        getModifiedTabs: () => {
          const state = get();
          return Array.from(state.tabs.values()).filter(isTabModified);
        },

        hasUnsavedChanges: () => {
          return get().getModifiedTabs().length > 0;
        },

        canCloseTab: (tabId: string) => {
          const tab = get().getTab(tabId);
          return tab ? !isTabModified(tab) : true;
        },

        generateTabId: (filePath: string) => {
          return generateTabId(filePath);
        },

        // 会话管理
        saveSession: () => {
          const state = get();
          const sessionData = {
            tabs: Array.from(state.tabs.entries()),
            tabOrder: state.tabOrder,
            activeTabId: state.activeTabId,
            groups: Array.from(state.groups.entries()),
            activeGroupId: state.activeGroupId,
            history: state.history,
            config: state.config,
          };

          try {
            localStorage.setItem('tab-session', JSON.stringify(sessionData));
          } catch (error) {
            console.error('Failed to save session:', error);
          }
        },

        loadSession: () => {
          try {
            const sessionData = localStorage.getItem('tab-session');
            if (sessionData) {
              const parsed = JSON.parse(sessionData);

              set({
                tabs: new Map(parsed.tabs || []),
                tabOrder: parsed.tabOrder || [],
                activeTabId: parsed.activeTabId || null,
                groups: new Map(parsed.groups || []),
                activeGroupId: parsed.activeGroupId || null,
                history: parsed.history || { ...defaultHistory },
                config: { ...defaultConfig, ...parsed.config },
              });
            }
          } catch (error) {
            console.error('Failed to load session:', error);
          }
        },

        clearSession: () => {
          try {
            localStorage.removeItem('tab-session');
          } catch (error) {
            console.error('Failed to clear session:', error);
          }
        },

        // 编辑器操作 - 这些方法需要与Monaco编辑器实例交互
        canUndo: (tabId: string) => {
          // 这里应该检查对应的Monaco编辑器实例是否可以撤销
          // 暂时返回false，实际实现需要与EditorInstanceManager集成
          const tab = get().getTab(tabId);
          return tab ? true : false; // 简化实现，实际需要检查编辑器状态
        },

        canRedo: (tabId: string) => {
          // 这里应该检查对应的Monaco编辑器实例是否可以重做
          // 暂时返回false，实际实现需要与EditorInstanceManager集成
          const tab = get().getTab(tabId);
          return tab ? true : false; // 简化实现，实际需要检查编辑器状态
        },

        undo: (tabId: string) => {
          // 这里应该调用对应的Monaco编辑器实例的撤销方法
          // 实际实现需要与EditorInstanceManager集成
          const tab = get().getTab(tabId);
          if (tab) {
            console.log(`Undo operation for tab: ${tabId}`);
            // TODO: 集成Monaco编辑器的撤销功能
            // const editorManager = getEditorInstanceManager();
            // const instance = editorManager.getInstance(tabId);
            // if (instance) {
            //   instance.editor.trigger('keyboard', 'undo', null);
            // }
          }
        },

        redo: (tabId: string) => {
          // 这里应该调用对应的Monaco编辑器实例的重做方法
          // 实际实现需要与EditorInstanceManager集成
          const tab = get().getTab(tabId);
          if (tab) {
            console.log(`Redo operation for tab: ${tabId}`);
            // TODO: 集成Monaco编辑器的重做功能
            // const editorManager = getEditorInstanceManager();
            // const instance = editorManager.getInstance(tabId);
            // if (instance) {
            //   instance.editor.trigger('keyboard', 'redo', null);
            // }
          }
        },
      }),
  },
  {
    name: 'tab-store',
    version: 1,
    enablePersist: true,
    enableDevtools: true,
    enableCrossModuleSync: true,
    enablePerformanceMonitoring: true,
    persistenceConfig: {
      partialize: (state: any) => ({
        tabs: Array.from(state.tabs.entries()),
        tabOrder: state.tabOrder,
        activeTabId: state.activeTabId,
        groups: Array.from(state.groups.entries()),
        activeGroupId: state.activeGroupId,
        config: state.config,
        history: state.history,
      }),
      merge: (persistedState: any, currentState: any) => {
        return {
          ...currentState,
          ...persistedState,
          tabs: new Map(persistedState.tabs || []),
          groups: new Map(persistedState.groups || []),
        };
      },
    },
  }
);

// 自动保存会话的订阅
useTabStore.subscribe(
  (state) => state.tabs,
  () => {
    // 延迟保存以避免频繁写入
    setTimeout(() => {
      useTabStore.getState().saveSession();
    }, 1000);
  }
);
